package com.agileai.bpm.controller.emulation;

import java.util.List;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.bpm.bizmoduler.emulation.WfOwnInitTaskManage;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.StandardListHandler;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.StringUtil;

public class WfOwnInitTaskListHandler extends StandardListHandler{
	public WfOwnInitTaskListHandler(){
		super();
		this.serviceId = buildServiceId(WfOwnInitTaskManage.class);
	}
	public ViewRenderer prepareDisplay(DataParam param){
		mergeParam(param);
		initParameters(param);
		this.setAttributes(param);
		User user = (User) this.getUser();
		param.put("userId", user.getUserId());
		List<DataRow> rsList = getService().findRecords(param);
		String markUrl = param.get("markUrl");
		if(StringUtil.isNotNullNotEmpty(markUrl)){
			for(int i=0;i<rsList.size();i++){
				DataRow row = rsList.get(i);
				StringBuffer stringBuffer = new StringBuffer(row.getString("WFP_LOGO_URL"));
				row.put("WFP_LOGO_URL",stringBuffer.insert(1, markUrl).toString());
			}
		}
		this.setRsList(rsList);
		request.setAttribute("rsList", rsList);
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
	public ViewRenderer doQueryAction(DataParam param){
		param.put("WFP_ID",param.get("CUR_WFP_ID"));
		return prepareDisplay(param);
	}
	protected void processPageAttributes(DataParam param) {
		if (!StringUtil.isNullOrEmpty(param.get("WFP_ID"))){
			this.setAttribute("CUR_WFP_ID", param.get("WFP_ID"));
		}
		if (!StringUtil.isNullOrEmpty(param.get("WFP_NAME"))){
			this.setAttribute("CUR_WFP_NAME", param.get("WFP_NAME"));
		}
	}
	protected void initParameters(DataParam param) {
		if (!StringUtil.isNullOrEmpty(param.get("WFP_ID"))){
			param.put("CUR_WFP_ID", param.get("WFP_ID"));
		}
		if (!StringUtil.isNullOrEmpty(param.get("WFP_NAME"))){
			param.put("CUR_WFP_NAME", param.get("WFP_NAME"));
		}		
	}
	@PageAction
  	public ViewRenderer retrieveIds(DataParam param) throws JSONException{
  		String responseText = "";
  		DataRow rsRow = getService().getRecord(param);
  		
  		JSONObject jsonObject = new JSONObject();  
        jsonObject.put("CreateUrl", rsRow.getString("WFP_CREATE_URL"));
        String json = jsonObject.toString();
  		responseText=json;
  		return new AjaxRenderer(responseText);
  	}
	protected WfOwnInitTaskManage getService() {
		return (WfOwnInitTaskManage)this.lookupService(this.getServiceId());
	}
}
